import React, { useEffect, useState } from 'react'
import Navbar from '@/comopnents/Navbar'
import { Button, Toast, NavBar } from 'antd-mobile'
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom'
import styles from './index.module.less'
import axios from 'axios'
import qs from 'qs'
import { payConfirm } from '@/utils/my/order'

export default function PayResult() {

    const navigate = useNavigate()

    // 获取传递来的价格
    const [searchParams] = useSearchParams()
    let type = searchParams.get('type') as string
    let price = searchParams.get('price') as string
    let out_trade_no = searchParams.get('out_trade_no') as string
    let total_amount = searchParams.get('total_amount') as string
    let trade_no = searchParams.get('trade_no') as string

    const data = {
        out_trade_no,
        trade_no
    }


    const [result, setResult] = useState<string>('加载中......')

    const payResult = async () => {
        // 给支付宝发请求 获取支付结果
        axios.post('http://localhost:3980/aliPay/payResult', qs.stringify(data)).then(res => {
            console.log(res)
            setResult(res.data.msg)
        })
        await payConfirm({
            orderId: out_trade_no,
            payType: 1,
            map: JSON.parse(localStorage.getItem('adress') as string)
        })
    }

    useEffect(() => {
        payResult()
    }, [])

    // 回到个人中心
    const gotoMy = () => {
        if (type === '1' && result === '加载中......') {
            return Toast.show({
                content: '请等待加载结束',
                duration: 800
            })
        }
        navigate(`/my`, { replace: true })
    }

    // 返回
    const back = () => {
        if (type === '1' && result === '加载中......') {
            return Toast.show({
                content: '请等待加载结束',
                duration: 800
            })
        }
        navigate('/my/order?type=0', {replace: true})
    }

    return (
        <div>
            <div className={styles.navBar}>
                <NavBar onBack={back}>乐居</NavBar>
            </div>
            <div className={styles.resultBox}>
                <div className={styles.title}>
                    {
                        type === '1' ?
                            result :
                            '交易成功'
                    }
                </div>
                <div>支付金额:
                    {
                        type === '1' ?
                            total_amount :
                            price
                    }
                    元</div>
            </div>
            <div className={styles.btn}>
                <Button color='primary' fill='outline' onClick={gotoMy}>个人中心</Button>
            </div>
        </div>
    )
}
